//
//  FansViewController.m
//  SXH
//
//  Created by 房 国生 on 15/8/5.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "FansViewController.h"
#import "FansTableViewCell.h"
#import "MJRefresh.h"
#import "CommonService.h"
#import "QueryAttentionEntity.h"
#import "UIImageView+WebCache.h"
#import "FindMeViewController.h"
#import "UserEntity.h"

@interface FansViewController ()<FansTableViewDelegate> {
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    
    int page;
}
@property (nonatomic, strong) IBOutlet UILabel *labelTitle;
@property (nonatomic, strong) IBOutlet UITableView *tableViewFans;
@property (nonatomic, strong) NSMutableArray *mutableArrayFans;

@end

@implementation FansViewController
@synthesize mutableArrayFans, tableViewFans;
@synthesize strPath, strTitle, findMeVC;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _labelTitle.text = strTitle;
    
    page = 1;
    [self addHeader];
    [self addFooter];
    UserEntity *userEntity = [UserEntity sharedInstance];
    if (![findMeVC.userId isEqualToString:userEntity.userId]) {
        strTitle = @"Ta的关注";
    }
    mutableArrayFans = [[NSMutableArray alloc] init];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [mutableArrayFans count]/2 + ([mutableArrayFans count]%2 > 0 ? 1: 0);
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *couponTableViewCellIdentifier=@"FansTableViewCell";
    FansTableViewCell *cell = (FansTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"FansTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
        cell.delegate = self;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (indexPath.row*2 < [mutableArrayFans count]) {
        QueryAttentionEntity *entity = [mutableArrayFans objectAtIndex:indexPath.row*2];
        
        [cell.imageViewHeaderLeft sd_setImageWithURL:[NSURL URLWithString:entity.userEntity.userAlbum]];
        cell.labelNameLeft.text = entity.userEntity.nickName;
        cell.labelFansLeft.text = [NSString stringWithFormat:@"%@个粉丝", entity.userEntity.fansCount];
        [cell.imageViewHeaderLeft.layer setMasksToBounds:YES];
        [cell.imageViewHeaderLeft.layer setCornerRadius:44.0]; //设置矩形四个圆角半径
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickIcon:)];
        [cell.imageViewHeaderLeft addGestureRecognizer:tap];
        cell.imageViewHeaderLeft.userInteractionEnabled = YES;
        cell.imageViewHeaderLeft.tag = indexPath.row*2;
        NSArray *array = [[NSArray alloc]initWithObjects:cell.imageViewLeft1, cell.imageViewLeft2, cell.imageViewLeft3,nil];
        
        for (int i = 0; i < [array count] && i < [entity.mutableArrayFind count]; i++) {
            UIImageView *imageView = [array objectAtIndex:i];
             FindEntity *findEntity = [entity.mutableArrayFind objectAtIndex:i];
            [imageView sd_setImageWithURL:[NSURL URLWithString:findEntity.album_thumb]];
        }
        
        if ([strTitle isEqualToString:@"我的关注"] == YES) {
            [cell.btnWatcheLeft setTitle:@"取消关注" forState:UIControlStateNormal];
        } else {
            if ([entity.userEntity.flag isEqualToString:@"1"]) {
                [cell.btnWatcheLeft setTitle:@"取消关注" forState:UIControlStateNormal];
            } else {
                [cell.btnWatcheLeft setTitle:@"关注" forState:UIControlStateNormal];
            }
        }
        cell.btnWatcheLeft.tag = indexPath.row*2;
        if ([entity.userEntity.isVip isEqualToString:@"0"] == YES) {
            cell.imageViewVIPLeft.hidden = YES;
        }
        
    }
    
    if (indexPath.row*2 + 1 < [mutableArrayFans count]) {
        
        cell.viewRight.hidden = NO;
        cell.btnWatcheRight.hidden = NO;
        
        QueryAttentionEntity *entity = [mutableArrayFans objectAtIndex:indexPath.row*2 + 1];
        
        [cell.imageViewHeaderRight.layer setMasksToBounds:YES];
        [cell.imageViewHeaderRight.layer setCornerRadius:44.0]; //设置矩形四个圆角半径
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickIcon:)];
        [cell.imageViewHeaderRight addGestureRecognizer:tap];
        cell.imageViewHeaderRight.userInteractionEnabled = YES;
        cell.imageViewHeaderRight.tag = indexPath.row*2+1;
        
        
        
        [cell.imageViewHeaderRight sd_setImageWithURL:[NSURL URLWithString:entity.userEntity.userAlbum]];
        cell.labelNameRight.text = entity.userEntity.nickName;
        cell.labelFansRight.text = [NSString stringWithFormat:@"%@个粉丝", entity.userEntity.fansCount];
        
        NSArray *array = [[NSArray alloc]initWithObjects:cell.imageViewRight1, cell.imageViewRight2, cell.imageViewRight3,nil];
        
        for (int i = 0; i < [array count] && i < [entity.mutableArrayFind count]; i++)
        {
            UIImageView *imageView = [array objectAtIndex:i];
            FindEntity *findEntity = [entity.mutableArrayFind objectAtIndex:i];
            [imageView sd_setImageWithURL:[NSURL URLWithString:findEntity.album_thumb]];        }
        
        if ([strTitle isEqualToString:@"我的关注"] == YES)
        {
            [cell.btnWatcheRight setTitle:@"取消关注" forState:UIControlStateNormal];
        }
        else
        {
            if ([entity.userEntity.flag isEqualToString:@"1"])
            {
                [cell.btnWatcheRight setTitle:@"取消关注" forState:UIControlStateNormal];
            } else
            {
                [cell.btnWatcheRight setTitle:@"关注" forState:UIControlStateNormal];
            }
        }
        if ([entity.userEntity.isVip isEqualToString:@"0"] == YES)
        {
            cell.imageViewVIPRight.hidden = YES;
        }
        cell.btnWatcheRight.tag = indexPath.row*2+1;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 243;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //NewsEntity *entity = [arraySpot objectAtIndex:indexPath.row];
}

- (void)addFooter
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableViewFans;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        ++page;
        [self getUserFansData:page RefreshView:refreshView];
        
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    _footer = footer;
}

- (void)addHeader
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableViewFans;
    
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        // 进入刷新状态就会回调这个Block
        [mutableArrayFans removeAllObjects];
        [self getUserFansData:1 RefreshView:refreshView];
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
        NSLog(@"%@----刷新完毕", refreshView.class);
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                NSLog(@"%@----切换到：普通状态", refreshView.class);
                break;
                
            case MJRefreshStatePulling:
                NSLog(@"%@----切换到：松开即可刷新的状态", refreshView.class);
                break;
                
            case MJRefreshStateRefreshing:
                NSLog(@"%@----切换到：正在刷新状态", refreshView.class);
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 刷新表格
    [self.tableViewFans reloadData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void) getUserFansData:(int) pageNo RefreshView:(MJRefreshBaseView *)refreshView {
    
    UserEntity *userEntity = [UserEntity sharedInstance];
    
    NSString *strPageNo = [NSString stringWithFormat:@"%d", pageNo];
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           strPageNo, @"page",
                           @"20", @"limit",
                           findMeVC.userId,@"userid",nil];
    
    [service getNetWorkData:param
                       Path:strPath
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSArray *array = [dic objectForKey:@"rows"];
                      for (NSDictionary* attributes in array)
                      {
                          QueryAttentionEntity *entity = [[QueryAttentionEntity alloc] init];
                          entity = [entity initWithAttributes:attributes];
                          [mutableArrayFans addObject:entity];
                      }
                      [self doneWithView:refreshView];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [self doneWithView:refreshView];
                  }];
}

- (void) watcheAction:(NSInteger)tag {
    QueryAttentionEntity *entity = [mutableArrayFans objectAtIndex:tag];
    
    UserEntity *userEntity = [UserEntity sharedInstance];
    
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           entity.userEntity.userId,@"attention_id",
                           userEntity.userId,@"userid",
                           nil];
    
    [service getNetWorkData:param
                       Path:USER_ATTENTION
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSNumber *code = [dic objectForKey:@"code"];
                      if ([code intValue] == 0) {
                          [mutableArrayFans removeAllObjects];
                          [self getUserFansData:page RefreshView:nil];
                          [findMeVC getUserInfo];
                          ALERT_ERR_MSG(@"操作成功");
                      } else {
                          ALERT_ERR_MSG(@"操作失败");
                      }
                  } Failed:^(NSInteger errorCode, NSString *message) {
                  }];
}

- (void)clickIcon:(UITapGestureRecognizer*)tap
{
     QueryAttentionEntity *entity = [mutableArrayFans objectAtIndex:tap.view.tag];
    NSLog(@"%@",entity.userEntity.userId);
    FindMeViewController *mvc = [[FindMeViewController alloc]init];
    mvc.userId = entity.userEntity.userId;
    mvc.isFromOtherVC = YES;
    [self.navigationController pushViewController:mvc animated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"FansViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"FansViewController"];
}
@end
